<template>
  <!-- 文章分类 -->
  <div class="category">
    <div class="main">
      <div class="header">
        <el-form :inline="true">
          <el-form-item label="分类名称">
            <el-input placeholder="请输入分类名称" v-model="findCategory.categoryName"></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select placeholder="请选择分类状态" v-model="findCategory.status" clearable>
              <el-option label="启用" value="1"></el-option>
              <el-option label="禁用" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="find">查询</el-button>
            <el-button @click="replace">重置</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="dialogFrom = true">
              <el-icon><Plus /></el-icon>
              <span>新增分类</span>
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="danger" @click="deleteBatch">
              <el-icon><Minus /></el-icon>
              <span>批量删除</span>
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="body" v-if="categoryList.length > 0">
        <el-table :data="categoryList" @selection-change="handleSelectionChange">
          <el-table-column type="selection"></el-table-column>
          <el-table-column label="图标" prop="icon">
            <template #default="scope">
              <el-image :src="scope.row.icon" style="width: 50px; height: 50px"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="分类名称" prop="categoryName"></el-table-column>
          <el-table-column label="关联文章数量" prop="articleCount"></el-table-column>
          <el-table-column label="状态" prop="status">
            <template #default="scope">
              <span
                :class="scope.row.status === 0 ? 'blur' : 'red'"
                @click="updateStatus(scope.row.status === 0 ? 1 : 0, scope.row.id)"
              >
                {{ scope.row.status === 0 ? '启用' : '禁用' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createTime"></el-table-column>
          <el-table-column label="修改时间" prop="updateTime"></el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="danger" :text="true" @click="deleteCategory(scope.row.id)"
                >删除</el-button
              >
              <el-button type="primary" :text="true" @click="toId(scope.row.id)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-empty v-else></el-empty>
      <div class="page">
        <el-pagination
          v-model:current-page="findCategory.page"
          v-model:page-size="findCategory.pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handelPage"
          @size-change="handelPageSize"
        ></el-pagination>
      </div>
      <el-dialog
        v-model="dialogFrom"
        width="500"
        style="padding: 20px"
        @open="getNameById"
        @close="reseat"
      >
        <el-form :rules="rules" ref="formRef" :model="categoryNameForm">
          <el-form-item label="分类名称" prop="categoryName">
            <el-input
              placeholder="请输入分类名称"
              v-model="categoryNameForm.categoryName"
            ></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFrom = false">Cancel</el-button>
            <el-button type="primary" @click="addCategory">OK</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { Plus, Minus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, ref } from 'vue'
import {
  addCategoryService,
  deleteCategoryService,
  getCategoryListPageService,
  getNameByIdService,
  updateBatchService,
} from '@/api/Category'

const categoryList = ref([])

const total = ref(5)
const findCategory = ref({
  page: 1,
  pageSize: 9,
  categoryName: '',
  status: null,
})

const dialogFrom = ref(false)

const formRef = ref()
const categoryNameForm = ref({
  categoryName: '',
})
// 表单验证规则
const rules = {
  categoryName: [
    { required: true, message: '发类名称不能为空', trigger: 'blur' },
    { min: 2, max: 6, message: '发类名称长度在2-6之间', trigger: 'blur' },
  ],
}
// 新增分类
const addCategory = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      // 表单验证通过，执行
      if (!updateBatchDto.value.id) {
        const name = categoryNameForm.value.categoryName
        await addCategoryService(name).then(() => {
          dialogFrom.value = false
          getPageList(findCategory.value)
        })
      } else {
        updateBatchDto.value.categoryName = categoryNameForm.value.categoryName
        updateBatchService(updateBatchDto.value).then(() => {
          updateBatchDto.value.categoryName = ''
          updateBatchDto.value.id = ''
          categoryNameForm.value.categoryName = ''
          dialogFrom.value = false
          getPageList(findCategory.value)
          console.log(categoryNameForm.value)
        })
      }
    }
  })
}
// 关闭回调
const reseat = () => {
  updateBatchDto.value.categoryName = ''
  updateBatchDto.value.id = ''
  categoryNameForm.value.categoryName = ''
}

// 修改分类
const updateBatchDto = ref({
  id: '',
  status: '',
  categoryName: '',
})
// 修改状态
const updateStatus = (status, id) => {
  updateBatchDto.value.id = id
  updateBatchDto.value.status = status
  updateBatchService(updateBatchDto.value).then(() => {
    getPageList(findCategory.value)
    updateBatchDto.value = {
      id: '',
      status: '',
      caetegoryName: '',
    }
  })
}
const toId = (id) => {
  updateBatchDto.value.id = id
  dialogFrom.value = true
}
const getNameById = async () => {
  if (updateBatchDto.value.id) {
    const res = await getNameByIdService(updateBatchDto.value.id)
    categoryNameForm.value.categoryName = res.msg
  } else {
    console.log('id不存在')
  }
}

const caetegoryIds = ref([])
// 删除分类
const deleteCategory = (id) => {
  caetegoryIds.value.push(id)
  console.log(caetegoryIds.value)
  deleteCategoryService(caetegoryIds.value).then(() => {
    getPageList(findCategory.value)
    caetegoryIds.value = []
  })
}
const handleSelectionChange = (row) => {
  const obj = JSON.parse(JSON.stringify(row))
  caetegoryIds.value = []
  obj.forEach((item) => {
    caetegoryIds.value.push(item.id)
  })
}
const deleteBatch = () => {
  if (caetegoryIds.value.length === 0) {
    ElMessage.error('未选中数据')
  } else {
    ElMessageBox.confirm(`你确认删除这${caetegoryIds.value.length}条数据吗?`, 'Warning', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      deleteCategoryService(caetegoryIds.value).then(() => {
        getPageList(findCategory.value)
        caetegoryIds.value = []
      })
    })
  }
}

const handelPage = (page) => {
  findCategory.page = page
  getPageList(findCategory.value)
}
const handelPageSize = (pageSize) => {
  findCategory.pageSize = pageSize
  getPageList(findCategory.value)
}

const find = () => {
  console.log(findCategory.value)
  getPageList(findCategory.value)
}
const replace = () => {
  findCategory.value.categoryName = ''
  findCategory.value.status = null
  getPageList({
    page: 1,
    pageSize: 9,
    categoryName: '',
    status: null,
  })
}

/**
 * 分类信息查询接口
 * @param dto
 */
const getPageList = async (dto) => {
  const { data } = await getCategoryListPageService(dto)
  total.value = data.total
  categoryList.value = data.records
}

onMounted(() => {
  getPageList(findCategory.value)
})
</script>

<style lang="scss" scoped>
.category {
  padding: 15px;
  min-height: 100vh;
  background-color: #f3f4f5;

  .main {
    padding: 20px;
    min-height: 100vh;
    background-color: #fff;
    border-radius: 7px;

    .header {
      :deep(.el-select__wrapper) {
        width: 150px;
      }
    }

    .page {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }
}

.blur {
  cursor: pointer;
  color: #37b4fd;
}
.red {
  cursor: pointer;
  color: red;
}
::v-deep.el-table .cell {
  text-align: center !important;
}
</style>